package cn.gjculture.shopping.api.service.impl;

import cn.gjculture.shopping.api.entity.wx.NewsMessage;
import cn.gjculture.shopping.api.entity.wx.PicTxtMessage;
import cn.gjculture.shopping.api.util.HttpClient;
import com.alibaba.fastjson.JSONObject;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;

@Slf4j
@Service
public class WXProxy {
    public String getAccessToken() {
        log.info("getAccessToken...");
        String url="https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid=wx74f53b124615eab2&secret=f88d2c9c40dde7cd53fe337226f3aa30";
        String response = HttpClient.get(url);
        JSONObject jsonObject=JSONObject.parseObject(response);
        log.info("getAccessToken return:{}",response);
        String accessToken=jsonObject.getString("access_token");
        return accessToken;
    }

    public boolean sendPicTxtMessage(String openId, PicTxtMessage message, String accessToken) {
        String url="https://api.weixin.qq.com/cgi-bin/message/custom/send?access_token="+accessToken;
        NewsMessage m=new NewsMessage();
        m.setTouser(openId);
        NewsMessage.News.Articles articles=new NewsMessage.News.Articles();
        articles.setTitle(message.getTitle());
        articles.setDescription(message.getDescription());
        articles.setPicurl(message.getPicurl());
        articles.setUrl(message.getUrl());
        m.getNews().getArticles().add(articles);
        String response=HttpClient.postJson(url, (JSONObject) JSONObject.toJSON(m));
        log.info("sendPicTxtMessage return：{}",response);
        JSONObject jsonObject=JSONObject.parseObject(response);
        if("0".equals(jsonObject.getString("errcode"))){
            return true;
        }else{
            return false;
        }
    }


    public JSONObject getOpenId(String accessToken, String next_openid) {
        log.info("get openid...");
        String url="https://api.weixin.qq.com/cgi-bin/user/get?access_token="+accessToken;
        if(next_openid!=null){
            url=url+"&next_openid="+next_openid;
        }
        String response=HttpClient.get(url);
        log.info("get openid return:{}",response);
        JSONObject jsonObject=JSONObject.parseObject(response);
        return jsonObject;
    }
}
